import { system_config } from './_config.js'
import { cacheAndSetDeadTime } from './format.js'
import qs from 'qs'



export default {
	config: {
		baseUrl: system_config.apiBaseUrl,
		// headers: {
		// 	"content-type":"application/x-www-form-urlencoded"
		// },
		// responseType: "text"
	},
	interceptor: {
		request:function(_config){},
		response: null
	},
	request(options) {
		uni.showLoading({
			title: '加载中...',
			mask:true
		});
		return new Promise((resolve, reject) => {
			let _config = null, un_token = options?.un_token??false
			options.url = this.config.baseUrl + options.url
			if(options.method == 'POST' && options.queryPost) {
				options.url = options.url + `?${options.params}`
			}
			options.header = Object.assign({},options.header,this.config.headers)
			// appId = uni.getStorageSync('appId'),
				let xtwAuthen = cacheAndSetDeadTime("tokenValue",null)
			// if(appId) options.header.appId = appId
			// 	else {
			// 		uni.setStorageSync('appId', system_config.appId)
			// 		options.header.appId = system_config.appId
			// 	}
			if(xtwAuthen) options.header.xtwAuthen = xtwAuthen
			else if(!un_token&&!xtwAuthen) uni.redirectTo({ url: '/pages/login/index' })
			options.header.Authorization = system_config.Authorization
			options.complete = (response) => {
				response.config = _config
				if (this.interceptor.response) {
					response = this.interceptor.response(response);
				} else if (response.statusCode === 200) {
					if(response.data.code === 200) {
						resolve(response.data)
					}else if(response.data.code === 403){
						uni.clearStorageSync()
						uni.redirectTo({ url: '/pages/login/index' })
					}else{
						uni.showToast({ icon: 'none', title: response.data.msg })
						reject(response)
					}
				}else{
					reject(response)
				}
				uni.hideLoading()
			}

			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()
			
			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			
			uni.request(_config);
		});
	},
	get(url, data, options) {
		data = data?data:{};
		
		if(!options) options = {}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data, options, queryPost) {
		if(!options) options = {}
		if(queryPost) options.params = qs.stringify(data)
			else options.data = data
		options.url = url
		options.method = 'POST'
		return this.request({ ...options, queryPost })
	},
	put(url, data, options) {
		if(!options) options = {}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	del(url, data, options) {
		if (!options) options = {}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}